package com.ray.depot.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ray.api.service.UcenterApiService;
import com.ray.auth.system.table.entity.Button;
import com.ray.auth.system.table.entity.Dict;
import com.ray.common.util.GsonUtil;
import com.ray.depot.enums.RecordType;
import com.ray.depot.service.InOutRecordService;
import com.ray.depot.service.InOutSerializeService;
import com.ray.depot.service.InOutService;
import com.ray.depot.service.SupplierService;
import com.ray.depot.service.WarehouseService;
import com.ray.depot.table.dto.InOutDto;
import com.ray.depot.table.dto.InOutSerializeDto;
import com.ray.depot.table.entity.InOut;
import com.ray.depot.table.entity.InOutRecord;
import com.ray.depot.table.entity.InOutSerialize;
import com.ray.depot.table.entity.Supplier;
import com.ray.depot.table.entity.Warehouse;
import com.ray.depot.table.vo.RecordVo;
import com.ray.depot.util.DataGridUtil;
import com.ray.depot.util.DictJsonUtil;
import com.ray.depot.util.DictLoadUtil;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.web.Result;
import com.zjhc.web.controller.WebController;

@Controller
@RequestMapping("/depot/in")
public class RecordInController extends WebController {

	@Autowired
	UcenterApiService ucenterApiService;
	@Autowired
	InOutRecordService inOutRecordService;
	@Autowired
	InOutService inOutService;
	@Autowired
	InOutSerializeService inOutSerializeService;
	@Autowired
	WarehouseService warehouseService;
	@Autowired
	SupplierService supplierService;
	
	
	
	@RequestMapping(value = "view")
	@RequiresPermissions("depot:in:view")
	public ModelAndView view(String menuId, HttpServletRequest request, HttpServletResponse respose,
			ModelAndView modelAndView) {
		LoginUser user = getLoginUser();
		// 查询页面拥有的资源
		Result<Map<String, List<Button>>> buttonsResult = ucenterApiService.queryUserButtonsWithMenu(user, menuId);
		if (buttonsResult.codeSuccess()) {
			modelAndView.addObject("buttons", buttonsResult.getData());
		}
		DictJsonUtil dictJsonUtil = new DictJsonUtil();
		  //获取
		dictJsonUtil.addDict(ucenterApiService,"InOutStatus","InType");
		List<Warehouse> types = warehouseService.queryWarehouse(new Warehouse(), user);
		  //获取
		dictJsonUtil.addDict("_Warehouse", DictLoadUtil.LoadWarchouse(types));
		modelAndView.addObject(dictJsonUtil.NAME, dictJsonUtil.getList());
		modelAndView.setViewName("depot/in/view");
		return modelAndView;
	}

	/**
	 * 新增页面
	 * 
	 * @param menuId
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping(value = "addView")
	@RequiresPermissions("depot:in:add")
	public ModelAndView addView(String menuId, RecordVo record, HttpServletRequest request, HttpServletResponse respose,
			ModelAndView modelAndView) {
		LoginUser user = getLoginUser();
		// 查询页面拥有的资源
		Result<Map<String, List<Button>>> buttonsResult = ucenterApiService.queryUserButtonsWithMenu(user, menuId);
		if (buttonsResult.codeSuccess()) {
			modelAndView.addObject("buttons", buttonsResult.getData());
		}
		Map<String,List<Dict>> dicts = DictLoadUtil.loadDict(ucenterApiService,"InOutStatus","InType");
		List<Warehouse> types = warehouseService.queryWarehouse(new Warehouse(), user);
		dicts.put("Warehouse", DictLoadUtil.LoadWarchouse(types));
		modelAndView.addObject("dicts", dicts);
		DictJsonUtil dictJsonUtil = new DictJsonUtil();
		  //获取
		dictJsonUtil.addDict(ucenterApiService,"useStatus","materialType","materialUnit","materialLife","yesOrNo");
		modelAndView.addObject(dictJsonUtil.NAME, dictJsonUtil.getList());
		//生成默认入库单号
		record.setInOutNo("RK00000001");
		modelAndView.addObject("record", record);
		modelAndView.setViewName("depot/in/add");
		return modelAndView;
	}

	/**
	 * 新增入库
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping(value = "add")
	@RequiresPermissions("depot:in:add")
	@ResponseBody
	public ResponseEntity<Result<Object>> add(InOutRecord record, String inOuts, String inOutSerializes, HttpServletRequest request,
			HttpServletResponse respose){
		LoginUser user = getLoginUser();
		RecordVo recordVo = new RecordVo();
		try {
			recordVo.setInOuts(GsonUtil.jsonToArrayList(inOuts, InOut.class));
			recordVo.setInOutSerializes(GsonUtil.jsonToArrayList(inOutSerializes, InOutSerialize.class));
			PropertyUtils.copyProperties(recordVo,record);
		} catch (Exception e) {
			return doError("数据转换异常，可能日期每天填写.");
		} 
		Result<Object> result = inOutRecordService.saveInRecord(recordVo,false,user);
		return doResult(result);
	}

	/*
	 * 修改页面
	 */
	@RequestMapping(value = "editView")
	@RequiresPermissions("depot:in:edit")
	public ModelAndView editView(String menuId, String id, HttpServletRequest request, HttpServletResponse respose,
			ModelAndView modelAndView) {
		LoginUser user = getLoginUser();
		// 查询页面拥有的资源
		Result<Map<String, List<Button>>> buttonsResult = ucenterApiService.queryUserButtonsWithMenu(user, menuId);
		if (buttonsResult.codeSuccess()) {
			modelAndView.addObject("buttons", buttonsResult.getData());
		}
		InOutRecord record = inOutRecordService.queryInOutRecord(id, user);
		
	    Map<String,List<Dict>> dicts = DictLoadUtil.loadDict(ucenterApiService,"InOutStatus","InType");
	    List<Warehouse> types = warehouseService.queryWarehouse(new Warehouse(), user);
		dicts.put("Warehouse", DictLoadUtil.LoadWarchouse(types));
	    //获取供应商
	    Supplier supplier = supplierService.querySupplier(record.getSourceId(), user);
	    if(ObjectUtil.isNotNull(supplier)){
	    	modelAndView.addObject("supplierName", supplier.getSupplierName());
	    }
	   
		modelAndView.addObject("dicts", dicts);
		DictJsonUtil dictJsonUtil = new DictJsonUtil();
		  //获取
		dictJsonUtil.addDict(ucenterApiService,"useStatus","materialType","materialUnit","materialLife","yesOrNo");
		modelAndView.addObject(dictJsonUtil.NAME, dictJsonUtil.getList());
		modelAndView.addObject("record", record);
		modelAndView.setViewName("depot/in/edit");
		return modelAndView;
	}

	/*
	 * 修改页面
	 */
	@RequestMapping(value = "activiti/editView")
	public ModelAndView activitiEditView(String menuId, String busId, HttpServletRequest request, HttpServletResponse respose,
			ModelAndView modelAndView) {
		LoginUser user = new LoginUser();
		user.setSuperManager(false);
		InOutRecord record = inOutRecordService.queryInOutRecordByInOutNo(busId, user);
		//获取创建人信息
		user.setTenantId(record.getTenantId());
		user.setOrgCode(record.getCreateByOrg());
		user.setDeptCode(record.getCreateByOrg());
		user.setUserId(record.getCreateByUser());
		
	    Map<String,List<Dict>> dicts = DictLoadUtil.loadDict(ucenterApiService,"InOutStatus","InType");
	    List<Warehouse> types = warehouseService.queryWarehouse(new Warehouse(), user);
		dicts.put("Warehouse", DictLoadUtil.LoadWarchouse(types));
	    //获取供应商
	    Supplier supplier = supplierService.querySupplier(record.getSourceId(), user);
	    if(ObjectUtil.isNotNull(supplier)){
	    	modelAndView.addObject("supplierName", supplier.getSupplierName());
	    }
	   
		modelAndView.addObject("dicts", dicts);
		DictJsonUtil dictJsonUtil = new DictJsonUtil();
		  //获取
		dictJsonUtil.addDict(ucenterApiService,"useStatus","materialType","materialUnit","materialLife","yesOrNo");
		modelAndView.addObject(dictJsonUtil.NAME, dictJsonUtil.getList());
		modelAndView.addObject("record", record);
		modelAndView.setViewName("depot/in/activitiEdit");
		return modelAndView;
	}

	
	/**
	 * 修改
	 */
	@RequestMapping(value = "edit")
	@RequiresPermissions("depot:in:edit")
	@ResponseBody
	public ResponseEntity<Result<Object>> update(InOutRecord record, String inOuts, String inOutSerializes, HttpServletRequest request,
			HttpServletResponse respose) {
		LoginUser user = getLoginUser();
		RecordVo recordVo = new RecordVo();
		try {
			recordVo.setInOuts(GsonUtil.jsonToArrayList(inOuts, InOut.class));
			recordVo.setInOutSerializes(GsonUtil.jsonToArrayList(inOutSerializes, InOutSerialize.class));
			PropertyUtils.copyProperties(recordVo,record);
		} catch (Exception e) {
			return doError("数据转换异常，可能日期每天填写.");
		} 
		Result<Object> result = inOutRecordService.editInRecord(recordVo, user);
		return doResult(result);
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "activiti/edit")
	@ResponseBody
	public ResponseEntity<Result<Object>> activitiUpdate(InOutRecord record, String inOuts, String inOutSerializes, HttpServletRequest request,
			HttpServletResponse respose) {
		LoginUser user = new LoginUser();
		user.setSuperManager(false);
		InOutRecord hisRecord = inOutRecordService.queryInOutRecord(record.getId(), user);
		//获取创建人信息
		user.setTenantId(hisRecord.getTenantId());
		user.setOrgCode(hisRecord.getCreateByOrg());
		user.setDeptCode(hisRecord.getCreateByOrg());
		user.setUserId(hisRecord.getCreateByUser());
		RecordVo recordVo = new RecordVo();
		try {
			recordVo.setInOuts(GsonUtil.jsonToArrayList(inOuts, InOut.class));
			recordVo.setInOutSerializes(GsonUtil.jsonToArrayList(inOutSerializes, InOutSerialize.class));
			PropertyUtils.copyProperties(recordVo,record);
		} catch (Exception e) {
			return doError("数据转换异常，可能日期每天填写.");
		} 
		Result<Object> result = inOutRecordService.editInRecord(recordVo, user);
		return doResult(result);
	}
	
	/**
	 * 详情页面
	 */
	@RequestMapping(value = "detailView")
	@RequiresPermissions("depot:in:detail")
	public ModelAndView detailView(String menuId, String id, HttpServletRequest request, HttpServletResponse respose,
			ModelAndView modelAndView) {
		LoginUser user = getLoginUser();
		// 查询页面拥有的资源
		Result<Map<String, List<Button>>> buttonsResult = ucenterApiService.queryUserButtonsWithMenu(user, menuId);
		if (buttonsResult.codeSuccess()) {
			modelAndView.addObject("buttons", buttonsResult.getData());
		}
		InOutRecord record = inOutRecordService.queryInOutRecord(id, user);
		
	    Map<String,List<Dict>> dicts = DictLoadUtil.loadDict(ucenterApiService,"InOutStatus","InType");
	    List<Warehouse> types = warehouseService.queryWarehouse(new Warehouse(), user);
	  	dicts.put("Warehouse", DictLoadUtil.LoadWarchouse(types));
	    //获取供应商
	    Supplier supplier = supplierService.querySupplier(record.getSourceId(), user);
	    if(ObjectUtil.isNotNull(supplier)){
	    	modelAndView.addObject("supplierName", supplier.getSupplierName());
	    }
	   
		modelAndView.addObject("dicts", dicts);
		DictJsonUtil dictJsonUtil = new DictJsonUtil();
		  //获取
		dictJsonUtil.addDict(ucenterApiService,"useStatus","materialType","materialUnit","materialLife","yesOrNo");
		modelAndView.addObject(dictJsonUtil.NAME, dictJsonUtil.getList());
		modelAndView.addObject("record", record);
		modelAndView.setViewName("depot/in/detail");
		return modelAndView;
	}

	
	
	/**
	 * 删除页面
	 */
	@RequestMapping(value = "delete")
	@RequiresPermissions("depot:in:delete")
	@ResponseBody
	public ResponseEntity<Result<Object>> delete(String id, HttpServletRequest request, HttpServletResponse respose) {
		LoginUser user = getLoginUser();
		Result<Object> result = inOutRecordService.deleteInRecord(id, user);
		return doSuccess(result);

	}

	/**
	 * 查询页面
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "query")
	@RequiresPermissions("depot:in:query")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> query(InOutRecord params, HttpServletRequest request,
			HttpServletResponse respose) {
		LoginUser user = getLoginUser();
		PageDto<InOutRecord> page = this.createJQPage(request);
		params.setRecordType(RecordType.IN.getType());
		page = inOutRecordService.queryInOutRecord(params, page, user);
		return doSuccess(DataGridUtil.dataConvert(page));

	}
	
	/**
	 * 提交审核
	 */
	@RequestMapping(value = "apply")
	@RequiresPermissions("depot:in:apply")
	@ResponseBody
	public ResponseEntity<Result<Object>> apply(String inOutNo,String userIds ,String deployId,String defId,String actKey, HttpServletRequest request,
			HttpServletResponse respose) {
		LoginUser user = getLoginUser();
		Result<Object> result = inOutRecordService.applyRecord(inOutNo,userIds,deployId,defId,actKey,user);
		return doResult(result);
	}
	
	/**
	 * 入库操作
	 */
	@RequestMapping(value = "in")
	@RequiresPermissions("depot:in:in")
	@ResponseBody
	public ResponseEntity<Result<Object>> in(String id, HttpServletRequest request,
			HttpServletResponse respose) {
		LoginUser user = getLoginUser();
		Result<Object> result =  inOutRecordService.storeIn(id,user);
		return doResult(result);
	}
	
	/**
	 * 保存草稿
	 */
	@RequestMapping(value = "draft")
	@RequiresPermissions("depot:in:draft")
	@ResponseBody
	public ResponseEntity<Result<Object>> draft(InOutRecord record, String inOuts, String inOutSerializes, HttpServletRequest request, HttpServletResponse respose) {
		LoginUser user = getLoginUser();
		RecordVo recordVo = new RecordVo();
		try {
			recordVo.setInOuts(GsonUtil.jsonToArrayList(inOuts, InOut.class));
			recordVo.setInOutSerializes(GsonUtil.jsonToArrayList(inOutSerializes, InOutSerialize.class));
			PropertyUtils.copyProperties(recordVo,record);
		} catch (Exception e) {
			return doError("数据转换异常，可能日期每天填写.");
		} 
		Result<Object> result = inOutRecordService.saveInRecord(recordVo,true,user);
		return doResult(result);
	}

	/**
	 * 物料查询页面
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "materialQuery")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> materialQuery(InOutDto params, HttpServletRequest request,
			HttpServletResponse respose) {
		LoginUser user = getLoginUser();
		PageDto<InOutDto> page = this.createJQPage(request);
		page = inOutService.querySelectInOut(params, page, user);
		return doSuccess(DataGridUtil.dataConvert(page));

	}
	
	/**
	 * 物料查询页面
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "activiti/materialQuery")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> activitiMaterialQuery(InOutDto params, HttpServletRequest request,
			HttpServletResponse respose) {
		LoginUser user = getLoginUser();
		PageDto<InOutDto> page = this.createJQPage(request);
		page = inOutService.querySelectInOut(params, page, user);
		return doSuccess(DataGridUtil.dataConvert(page));

	}
	
	/**
	 * 资产查询页面
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "serializaQuery")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> serializaQuery(InOutSerializeDto params, HttpServletRequest request,
			HttpServletResponse respose) {
		LoginUser user = getLoginUser();
		PageDto<InOutSerializeDto> page = this.createJQPage(request);
		page = inOutSerializeService.querySelectInOutSerialize(params, page, user);
		return doSuccess(DataGridUtil.dataConvert(page));

	}
	/**
	 * 资产查询页面
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "activiti/serializaQuery")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> activitiSerializaQuery(InOutSerializeDto params, HttpServletRequest request,
			HttpServletResponse respose) {
		LoginUser user = getLoginUser();
		PageDto<InOutSerializeDto> page = this.createJQPage(request);
		page = inOutSerializeService.querySelectInOutSerialize(params, page, user);
		return doSuccess(DataGridUtil.dataConvert(page));

	}
	
	/**
	 * 详情页面
	 */
	@RequestMapping(value = "/activiti/detailView")
	public ModelAndView activitiDetailView(String menuId, String busId, HttpServletRequest request, HttpServletResponse respose,
			ModelAndView modelAndView) {
		LoginUser user = new LoginUser();
		
		InOutRecord record = inOutRecordService.queryInOutRecordByInOutNo(busId, user);
		//获取创建人信息
		user.setTenantId(record.getTenantId());
		user.setOrgCode(record.getCreateByOrg());
		user.setDeptCode(record.getCreateByOrg());
		user.setUserId(record.getCreateByUser());
		
		
	    Map<String,List<Dict>> dicts = DictLoadUtil.loadDict(ucenterApiService,"InOutStatus","InType");
	    List<Warehouse> types = warehouseService.queryWarehouse(new Warehouse(), user);
	  	dicts.put("Warehouse", DictLoadUtil.LoadWarchouse(types));
	    //获取供应商
	    Supplier supplier = supplierService.querySupplier(record.getSourceId(), user);
	    if(ObjectUtil.isNotNull(supplier)){
	    	modelAndView.addObject("supplierName", supplier.getSupplierName());
	    }
	   
		modelAndView.addObject("dicts", dicts);
		DictJsonUtil dictJsonUtil = new DictJsonUtil();
		  //获取
		dictJsonUtil.addDict(ucenterApiService,"useStatus","materialType","materialUnit","materialLife","yesOrNo");
		modelAndView.addObject(dictJsonUtil.NAME, dictJsonUtil.getList());
		modelAndView.addObject("record", record);
		modelAndView.setViewName("depot/in/activitiDetail");
		return modelAndView;
	}
	
}
